package com.hy.study.service.impl;

import com.alibaba.fastjson.JSON;
import com.hy.study.dao.TaskRepository;
import com.hy.study.dto.Task;
import com.hy.study.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

/**
 * @author huyong
 * @date 2024 年 01 月 08 日 9:23: 53
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskRepository taskRepository;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    @Transactional// 自动事务托管
    public Task save(Task task) {
        Task save = taskRepository.save(task);
        log.info(JSON.toJSONString(save));
        return save;
    }

    @Cacheable(value = "taskInfo")
    @Override
    public Task findById(long id) {
        log.info("从数据库中获取数据----id:{}", id);
        Optional<Task> task = taskRepository.findById(id);
        return task.orElseGet(Task::new);
    }

    @CacheEvict(value = "taskInfo")
    @Override
    public void deleteFromCache(long id) {
        log.info("从缓存中删除 id-->{}", id);
    }

    @Override
    public void test() {
        ValueOperations<String, String> valueOper = redisTemplate.opsForValue();
        valueOper.set("mykey4", "random1=" + Math.random());
        log.info(valueOper.get("mykey4"));

    }
}
